<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input
            v-model="queryParams.age"
            placeholder="请输入年龄"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="别名" prop="nickname">
        <el-input
            v-model="queryParams.nickname"
            placeholder="请输入别名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="头像" prop="imgurl">
        <el-input
            v-model="queryParams.imgurl"
            placeholder="请输入头像"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['demo:us:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['demo:us:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['demo:us:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['demo:us:export']"
        >导出excel</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            size="mini"
            @click="uploadDialogVisible = true"
        >导入文件</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            size="mini"
            @click="handleExportword1"
        >导出word</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            size="mini"
            @click="handleExportpdf1"
        >导出pdf</el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 导入文件对话框 -->
    <el-dialog
        :title="'导入文件'"
        v-model="uploadDialogVisible"
        width="400px"
    >
      <el-upload
          ref="uploadComponent"
          class="upload-demo"
          drag
          :multiple="true"
          accept=".xls,.xlsx"
          :before-upload="beforeUpload"
          :http-request="customUploadRequest"
          size="mini"
      >
        <el-row :span="24" style="display: flex; align-items: center; justify-content: center; flex-direction: column;">
          <el-col :span="6">
            <el-icon style="margin-top: 25px" class="el-icon--upload"><UploadFilled /></el-icon>
          </el-col>
          <el-col :span="18">
            <p style="font-weight: 700;font-size: 20px">上传</p>
            <div class="el-upload__text">
              将文件拖到此处或者点击<em>上传文件</em>
            </div>
          </el-col>
        </el-row>
      </el-upload>
      <template #footer>  <!-- 替换slot="footer"为#footer -->
        <el-button @click="handleClose">关闭</el-button>
      </template>
    </el-dialog>



    <el-table v-loading="loading" :data="usList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户ID" align="center" prop="id" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="别名" align="center" prop="nickname" />
      <el-table-column label="img" align="center" prop="imgurl" >

        <template #default="scope">
          <div v-if="scope.row.imgurl" class="image-preview">
            <el-image
                :src="scope.row.imgurl"
                fit="cover"
                style="width: 50px; height: 50px; border-radius: 4px;"
                :preview-src-list="[scope.row.imgurl]"
                lazy
            >
              <template #error>  <!-- 替换slot="error"为#error -->
                <div class="image-error">
                  <el-icon><PictureOutline /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
          <div v-else class="no-image">
            <el-icon><PictureOutline /></el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['demo:us:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['demo:us:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改DEMO用户信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="usRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="别名" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入别名" />
        </el-form-item>
        <el-form-item label="头像" prop="imgurl">
          <el-input v-model="form.imgurl" placeholder="请输入头像" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Us">
import { listUs, getUs, delUs, addUs, updateUs,exportWord,exportexcel,exportpdf,upfile } from "@/api/demo/us";
import { ElMessage } from 'element-plus';
const { proxy } = getCurrentInstance();

const usList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const uploadDialogVisible = ref(false)
const uploadComponent = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    age: null,
    nickname: null,
    imgurl: null
  },
  rules: {
    name: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询DEMO用户信息列表 */
function getList() {
  loading.value = true;
  listUs(queryParams.value).then(response => {
    usList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

const handleClose = () => {
  console.log('关闭按钮被点击')
  console.log('当前 uploadDialogVisible 值:', uploadDialogVisible.value)
  uploadDialogVisible.value = false
  uploadComponent.value.clearFiles();  // 清空显示
  console.log('设置后 uploadDialogVisible 值:', uploadDialogVisible.value)
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    age: null,
    nickname: null,
    imgurl: null
  };
  proxy.resetForm("usRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加DEMO用户信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getUs(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改DEMO用户信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["usRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateUs(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUs(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除DEMO用户信息编号为"' + _ids + '"的数据项？').then(function() {
    return delUs(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/kamenxian/demo/us/export', {
    ...queryParams.value
  }, `us_${new Date().getTime()}.xlsx`)
}
function handleExportword1() {
  proxy.download('/kamenxian/demo/us/word', {
    ...queryParams.value
  }, `us_${new Date().getTime()}.docx`)
}

function handleExportpdf1() {
  proxy.download('/kamenxian/demo/us/pdf', {
    ...queryParams.value
  }, `us_${new Date().getTime()}.pdf`)
}



async function handleExport2() {
  const param = {};  // 可添加查询参数
  try {
    const response = await exportexcel(param);

    // 正确访问响应头
    const contentType = response.headers['content-type'] || '';

    // 检查返回的是否是JSON错误信息
    if (contentType.includes('application/json')) {
      // 如果是JSON，则直接解析（假设response.data已经是解析后的对象）
      ElMessage.error(`导出失败：${response.data.error || '未知错误'}`);
      return;
    }
    // 下载文件
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.download = 'users.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出异常:', error);
    ElMessage.error('导出失败，请检查网络或参数');
  }
}

// 导出Word
async function handleExportword(){
  const param = {};
  try {
    const response = await exportWord(param);
    const contentType = response.headers['content-type'];
    if (contentType.includes('application/json')) {
      const text = await new Blob([response.data]).text();
      const error = JSON.parse(text);
      ElMessage.error(`导出失败：${error.error}`);
      return;
    }
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.download = 'users.docx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出异常:', error);
    ElMessage.error('导出失败，请检查网络或参数');
  }
}

// 导出PDF
async function  handleExportpdf(){
  const param = {};
  try {
    const response = await exportpdf(param);
    const contentType = response.headers['content-type'];
    if (contentType.includes('application/json')) {
      const text = await new Blob([response.data]).text();
      const error = JSON.parse(text);
      ElMessage.error(`导出失败：${error.error}`);
      return;
    }
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.download = 'users.pdf';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出异常:', error);
    ElMessage.error('导出失败，请检查网络或参数');
  }
}


// 上传前校验
const beforeUpload = (file) => {
  const isLxls = file.name.endsWith('.xls') || file.name.endsWith('.xlsx');
  const isSizeValid = file.size / 1024 / 1024 < 10;  // 限制10MB
  if (!isLxls) {
    ElMessage.error('请上传后缀名为.xls或.xlsx的文件');
    return false;
  }
  if (!isSizeValid) {
    ElMessage.error(`文件大小超过10MB限制，当前为${(file.size / 1024 / 1024).toFixed(2)}MB`);
    return false;
  }
  return true;
};

// 自定义上传请求
const customUploadRequest = (option) => {
  const formData = new FormData();
  formData.append('file', option.file);
  upfile(formData).then(response => {
    console.log( response);
    const files = response.data;
    if(files>0){
      uploadComponent.value.clearFiles();  // 清空显示
      getList();
      uploadDialogVisible.value = false;
    }
    // getUniqueData();  // 若有此方法需定义
  }).catch(error => {
    option.onError(error);
  });
};


getList();
</script>
